#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import datetime
import importlib
import threading
import time
from com.zxy.common import Com_Para
from com.zxy.z_debug import z_debug
class TimeLoopTask(z_debug):
    def __init__(self, Interval, sleeps, sname):
        self.Interval = Interval
        self.sleeps = sleeps
        self.sname = sname
        self.bTimeFlag = False
    def stimedo(self):
        self.bTimeFlag = True
        self.RunReflectInClass()
        self.bTimeFlag = False
    def run(self):
        t = threading.Thread(target=self.show, name=self.sname)
        t.start()
    def RunReflectInClass(self):
        if self.sname != "":
            try:
                objC = importlib.import_module(self.sname)  #对模块进行导入                
                objName = self.sname.split(".")
                objN = getattr(objC,objName[len(objName) - 1])
                if hasattr(objN,"strContinue"):
                    fun_us = getattr(objN,"init_start")
                    fun_us(objN)
            except Exception as e:
                if str(type(self)) == "<class 'type'>":
                    self.debug_in(self,repr(e))#打印异常信息
                else:
                    self.debug_in(repr(e))#打印异常信息
            finally:
                pass 
    def show(self):
        starttime = datetime.datetime.now()
        if self.Interval != 0:
            endtime = starttime + datetime.timedelta(seconds=self.Interval)
            while True:
                starttime = datetime.datetime.now()
                if starttime >= endtime and not self.bTimeFlag:
                    if starttime >= endtime + datetime.timedelta(seconds=self.Interval):
                        endtime = endtime + datetime.timedelta(seconds=self.Interval)
                    else:
                        endtime = endtime + datetime.timedelta(seconds=self.Interval)
                    self.stimedo()
                elif (endtime - starttime).seconds > 10 * self.Interval:
                    endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.Interval)
                else:
                    time.sleep(self.sleeps)      